<!--
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-03-10 21:38:26
 * @LastEditTime: 2021-06-13 17:29:02
 * @LastEditors: zheng yiliang
-->
<template>
  <div>
    <el-card v-show="showSearch">
      <el-form ref="formRef" :model="form" size="medium" class="query-form">
        <el-form-item label="文章分类：" prop="category">
          <el-radio-group v-model="form.category">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button
              :key="item._id"
              v-for="item in categories"
              :label="item._id"
              >{{ item.name }}</el-radio-button
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章类型：" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="1">普通文章</el-radio-button>
            <el-radio-button label="2">简历</el-radio-button>
            <el-radio-button label="3">管理员介绍</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="转载状态：" prop="origin">
          <el-radio-group v-model="form.origin">
            <el-radio-button label=""> 全部</el-radio-button>
            <el-radio-button label="0">原创</el-radio-button>
            <el-radio-button label="1">转载</el-radio-button>
            <el-radio-button label="2">混合</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布状态：" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio-button label=""> 全部</el-radio-button>
            <el-radio-button label="0">草稿</el-radio-button>
            <el-radio-button label="1">已发布</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开源状态：" prop="secret">
          <el-radio-group v-model="form.secret">
            <el-radio-button label=""> 全部</el-radio-button>
            <el-radio-button label="0">公开</el-radio-button>
            <el-radio-button label="1">私密</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="重置选项：">
          <el-button type="primary" icon="el-icon-refresh" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <div class="divider" v-show="showSearch"></div>
    <el-card>
      <el-row type="flex" justify="space-between">
        <el-col>
          <el-input
            class="mgr10"
            style="width: 240px"
            clearable
            v-model="keyword"
            placeholder="请输入关键字搜索"
            @keyup.enter.native="articleQry"
          ></el-input>
          <el-button type="primary" icon="el-icon-search" @click="articleQry"
            >搜索</el-button
          >
        </el-col>
        <el-col class="tr">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="allArticle"
          ></right-toolbar>
        </el-col>
      </el-row>
      <article-table
        v-loading="loading"
        :articleData="articles"
        :curretPage="form.pagenum"
        :pageSize="form.pagesize"
        :total="total"
        @handleCurrentPage="(page) => (form.pagenum = page)"
        @handleCurrentSize="(size) => (form.pagesize = size)"
        @handleEdit="handleEdit"
        @handleRemove="handleDel"
      ></article-table>
    </el-card>
    <el-dialog
      title="修改文章"
      :visible.sync="dialogVisible"
      fullscreen
      :close-on-click-modal="false"
    >
      <el-form
        class="edit-form"
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        inline
      >
        <el-form-item label="作者：">
          <span class="el-input">{{ editForm.author }}</span>
        </el-form-item>
        <el-form-item label="标题：" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="desc">
          <el-input v-model="editForm.desc" type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="分类：" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择属于分类">
            <el-option
              v-for="item in categories"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签：" prop="tags">
          <el-select v-model="editForm.tags" multiple placeholder="请选择标签">
            <el-option
              v-for="item in tagList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="keyword" label="关键字：">
          <el-input
            v-model="editForm.keyword"
            placeholder="请输入关键字"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章类型：">
          <el-select v-model="editForm.type" placeholder="请选择文章类型">
            <el-option label="普通文章" :value="1"></el-option>
            <el-option label="简历" :value="2"></el-option>
            <el-option label="管理员介绍" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转载状态：">
          <el-select v-model="editForm.origin" placeholder="请选择转载状态">
            <el-option label="原创" :value="0"></el-option>
            <el-option label="转载" :value="1"></el-option>
            <el-option label="混合" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="img_url" label="封面：">
          <el-row type="flex">
            <el-col>
              <div
                class="el-input__inner upload-image"
                :class="{ 'el-upload-list--picture-card': editForm.img_url }"
              >
                <template v-if="editForm.img_url">
                  <img :src="editForm.img_url" width="100%" height="100%" />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </template>
              </div>
            </el-col>
            <el-col>
              <el-upload
                style="display: inline-block"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handlePicChange"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary">点击上传</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="是否开源：">
          <el-radio-group v-model="editForm.secret">
            <el-radio :label="0">公开</el-radio>
            <el-radio :label="1">私密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶：">
          <el-radio-group v-model="editForm.top">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- <el-form-item label="内容："> -->
        <markdown-editor v-model="editForm.content"></markdown-editor>
        <!-- </el-form-item> -->
        <div class="mgtb30 tc">
          <template v-if="stateArticle === 0">
            <el-button type="info" @click="handleSubmit(0)">存为草稿</el-button>
            <el-button type="primary" @click="handleSubmit(1)">发布</el-button>
          </template>
          <template v-else>
            <el-button type="info" @click="dialogVisible = false"
              >取消修改</el-button
            >
            <el-button type="primary" @click="handleSubmit(1)"
              >修改文章</el-button
            >
          </template>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import ArticleTable from './article-table'
import {
  getArticles,
  getArticlesDetail,
  delArticles,
  editArticles
} from '@/api/article'
import { getAllCategory } from '@/api/category'
import { getAllTag } from '@/api/tag'
import RightToolbar from '@/components/RightToolbar'
import MarkdownEditor from '@/components/MarkdownEditor'
import Screenfull from '@/components/Screenfull'
export default {
  name: 'ArticleList',
  components: { Screenfull, ArticleTable, RightToolbar, MarkdownEditor },
  data() {
    return {
      stateArticle: 1,
      imgdialogVisible: false,
      dialogVisible: false,
      loading: false,
      showSearch: true,
      keyword: '',
      editForm: {},
      form: {
        state: '',
        pagesize: 5,
        pageNum: 1,
        // keyword: '',
        category: '', // 分类
        // tag: [], // 标签
        type: '',
        origin: '',
        secret: ''
        // dateRange: []
      },
      articles: [], // 文章
      categories: [], // 分类
      tagList: [], // 标签
      total: 0,
      time: '',
      editRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入文章描述', trigger: 'blur' }],
        author: [{ required: true, message: '请选择作者', trigger: 'change' }],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
        // createTime: [
        //   { required: true, message: '请选择创建时间', trigger: 'change' }
        // ],
        secret: [
          { required: true, message: '请选择是否开源', trigger: 'change' }
        ]
        // img_url: [
        //   { required: true, message: '请输入封面地址', trigger: 'change' }
        // ]
      }
    }
  },
  mounted() {
    this.allArticle()
    this.getCategory() // 获取分类列表
    this.getTags() // 获取标签列表
  },
  watch: {
    form: {
      //监听的对象
      deep: true, //深度监听设置为 true
      handler: function (newV, oldV) {
        clearTimeout(this.time)
        this.time = setTimeout(() => {
          this.allArticle()
        }, 100)
      }
    }
  },
  methods: {
    handlePicChange(file) {
      this.editForm.img_url = URL.createObjectURL(file.raw)
      this.editForm.articleImg = file.raw
    },
    // 修改
    async handleEdit(val) {
      const { _RejCode, data } = await getArticlesDetail(val)
      if (_RejCode !== '00000000') return
      this.editForm = data
      this.stateArticle = data.state
      this.editForm.category = data.category[0]._id
      this.editForm.keyword = data.keyword.join(',')
      this.editForm.tags = data.tags.map((item) => item._id)
      this.dialogVisible = true

      // this.editForm.tags = data.tags.length ? data.tags.join(',') : ''
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.keyword = ''
      this.$refs['formRef'].resetFields()
      this.allArticle()
    },
    //限制上传时的文件格式大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 3
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 和 Png 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 3MB!')
        return false
      }
    },
    async allArticle() {
      this.loading = true
      const { _RejCode, data } = await getArticles(this.form)
      if (_RejCode !== '00000000') {
        this.loading = false
        return
      }
      this.loading = false
      this.articles = data.list
      this.total = data.count
    },
    async articleQry() {
      let obj = { ...this.form }
      if (this.keyword) {
        obj.keyword = this.keyword
      }
      const { _RejCode, data } = await getArticles(obj)
      if (_RejCode !== '00000000') return
      this.articles = data.list
      this.total = data.count
    },
    async getCategory() {
      const { _RejCode, data } = await getAllCategory().catch((err) => err)
      if (_RejCode !== '00000000') return
      this.categories = data.list
    },
    handleSubmit(val) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          this.editForm.state = val
          const formData = new FormData()
          for (let [key, value] of Object.entries(this.editForm)) {
            formData.append(key, value)
          }
          const { _RejCode, _RejMsg } = await editArticles(formData)
          if (_RejCode !== '00000000') return
          this.$message.success(_RejMsg)
          this.dialogVisible = false
          this.stateArticle = val
          this.allArticle()
        }
      })
    },
    async handleDel(val) {
      const confirmRes = await this.$confirm(
        `确认要永久删除该文章吗?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      if (confirmRes !== 'confirm') {
        // row.status =
        return this.$message({
          type: 'info',
          message: `已取消删除`
        })
      }
      const { _RejCode, _RejMsg } = await delArticles(val)
      if (_RejCode !== '00000000') return
      this.$message.success(_RejMsg)
      this.allArticle()
    },
    async getTags() {
      const { _RejCode, data } = await getAllTag().catch((err) => err)
      if (_RejCode !== '00000000') return
      this.tagList = data.list
    },
    handleRemove() {
      this.editForm.img_url = ''
      this.editForm.articleImg = ''
    }
  }
}
</script>

<style lang="scss" scoped>
// ::v-deep .el-form-item {
//   .el-range-editor,
//   .el-radio-group,
//   .el-textarea,
//   .el-input {
//     width: 280px;
//   }
//   .el-select {
//     width: 280px;
//     & > .el-input {
//       width: 100%;
//     }
//   }
// }
.query-form {
  ::v-deep .el-form-item {
    margin: 0px;
    padding: 10px 0px;
    border-bottom: 1px dashed #e2e4ea;
    .el-range-editor,
    .el-input {
      width: 280px;
    }
  }
  ::v-deep .el-radio-group {
    .el-radio-button {
      margin-right: 20px;
      .el-radio-button__inner {
        border-width: 0px;
        // padding: 8px 16px;
        border-radius: 4px;
      }
    }
  }
}
.edit-form {
  ::v-deep .el-form-item {
    .el-radio-group,
    .el-textarea,
    .el-input {
      width: 280px;
    }
    .el-select {
      width: 280px;
      & > .el-input {
        width: 100%;
      }
    }
  }
  .upload-image {
    width: 172px;
    margin-right: 10px;
    height: 40px;
    padding: 0;
    position: relative;
  }
  .el-row {
    height: 40px;
  }
}
.divider {
  height: 30px;
}
</style>
